<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Comment extends CI_Controller {

	public function __construct()
    {
        parent::__construct();
        $this->load->model('Comment_model');
    }
	

	public function index()
	{
		$userid = $this->thatUser['id'];
		$ids = array($userid);
		if ($this->thatUser['usertype'] == 2)
		{
			$this->load->model('User_model');
			$userids = $this->User_model->list_by_where(array('insid'=>$userid),'id');
			$ids = array_map('array_shift', $userids);
			array_push($ids, $userid);
		}
		$page     = _get_page();
		$pagesize = 10;
		$arrParam = array();
		$arrWhere = array('touserid'=>$ids,'status'=>'1');		//条件

		$list = $this->Comment_model->fetch_page($page, $pagesize, $arrWhere);
// 		echo $this->Comment_model->db->last_query();die;
		
        //获取回复信息
        if(!empty($list['rows'])) {
            foreach ($list['rows'] as $key=>$value) {
                if(!empty($value['id'])) {
                   $where = array('commentid'=>$value['id'], 'status'=>1);
                    //print_r($list['rows'][$key]);
                   $list['rows'][$key]['reply'] = $this->Comment_model->fetch_rows($where);
                }
            }
        }
        
		//分页
		$pagecfg = array();
		$pagecfg['base_url']     = _create_url('m/Comment', $arrParam);
		$pagecfg['total_rows']   = $list['count'];
		$pagecfg['cur_page'] = $page;
		$pagecfg['per_page'] = $pagesize;
// 		$this->load->library('pagination');
		$this->pagination->initialize($pagecfg);
		$list['pages'] = $this->pagination->create_links();

		$result = array(
			'list' => $list,
			);
		
		$this->load->view('m/comment',$result);
	}

	public function add(){
		$userid = $this->thatUser['id'];
 
		if ($this->input->is_post())
		{
            //回复只需要验证评价
            $config = array(
                array(
                    'field'   => 'memo', 
                    'label'   => '评价内容', 
                    'rules'   => 'trim|required'
                ),
            );  
            
            $commentid = (int)$this->input->post('commentid');
            //如果不是回复则需要验证专业技能，工作效率，工作态度。
            if(empty($commentid)) {
			//验证规则
                $config[] =  array(
                    'field'   => 'skill', 
                    'label'   => '专业技能', 
                    'rules'   => 'trim|required'
                );  
                $config[] =  array(
                         'field'   => 'efficiency', 
                         'label'   => '工作效率', 
                         'rules'   => 'trim|required'
                      );  
                $config[] =  array(
                         'field'   => 'attitude', 
                         'label'   => '工作态度', 
                         'rules'   => 'trim|required'
                );    
            }
            
            $this->form_validation->set_rules($config);
            //var_dump($this->form_validation->run());exit();
			if ( $this->form_validation->run() === TRUE)
  			{
  				$orderid = $this->input->post('orderid');
				$this->load->model('Order_model');
				$oOrder = $this->Order_model->get_by_id($orderid);
				$ids = array($userid);
				if ($this->thatUser['usertype'] == 2)
				{
					$this->load->model('User_model');
					$userids = $this->User_model->list_by_where(array('insid'=>$userid),'id');
					$ids = array_map('array_shift', $userids);
					array_push($ids, $userid);
				}
				if($oOrder && ( in_array($oOrder['buyerid'], $ids) || in_array($oOrder['sellerid'], $ids)))
				{
					if(in_array($oOrder['buyerid'], $ids))
					{
						$touserid = $oOrder['sellerid'];
						$tonickname = $oOrder['seller_nickname'];
						$com_userid = $oOrder['buyerid'];
						$com_nickname = $oOrder['buyer_nickname'];
					}
					else if(in_array($oOrder['sellerid'], $ids))
					{
						$touserid = $oOrder['buyerid'];
						$tonickname = $oOrder['buyer_nickname'];
						$com_userid = $oOrder['sellerid'];
						$com_nickname = $oOrder['seller_nickname'];
					}
					if($touserid && $tonickname)
					{
					    $skill = $this->input->post('skill');
					    $efficiency = $this->input->post('efficiency');
					    $attitude = $this->input->post('attitude');
						$data = array(
		  					'touserid'=>$touserid,
		  					'tonickname'=>$tonickname,
		  					'userid'=>$com_userid,
		  					'nickname'=>$com_nickname,
		  					'logo'=>$this->thatUser['userlogo'],
		  					'commentid'=>$commentid,
		  					'orderid'=>$orderid,
							'figure'=>$this->input->post('figure'),
							'skill'=>$skill,
							'efficiency'=>$efficiency,
							'attitude'=>$attitude,
							'memo'=>$this->input->post('memo'),
							'addtime'=>time(),
							'display'=>1,
							'status'=>1,
							'op_userid'=>$this->loginID,
							'op_nickname'=>$this->loginNickName,
							'op_time'=>time(),
						);
		  				$this->Comment_model->insert($data);
		  				
		  				//评论奖罚魔币规则
		  				if (!$commentid)
		  				{
		  				    //魔币
		  				    $icon = 0;
		  				    //五星评论奖励
		  				    if ($skill == 5)
		  				        $icon += 100;
		  				    if ($efficiency == 5)
		  				        $icon += 100;
		  				    if ($attitude == 5)
		  				        $icon += 100;
		  				    //三星评论惩罚
		  				    if ($skill == 3)
		  				        $icon -= 200;
		  				    if ($efficiency == 3)
		  				        $icon -= 200;
		  				    if ($attitude == 3)
		  				        $icon -= 200;
		  				    //两星评论惩罚
		  				    if ($skill == 2)
		  				        $icon -= 300;
		  				    if ($efficiency == 2)
		  				        $icon -= 300;
		  				    if ($attitude == 2)
		  				        $icon -= 300;
		  				    //一星评论惩罚
		  				    if ($skill == 1)
		  				        $icon -= 500;
		  				    if ($efficiency == 1)
		  				        $icon -= 500;
		  				    if ($attitude == 1)
		  				        $icon -= 500;
		  				    
		  				    $type = 1;
		  				    if ($icon < 0)
		  				        $type = 2;
	  				        $this->load->service('magic_service');
	  				        $this->magic_service->recordMagicCoins($touserid,abs($icon),5,$type);
		  				}
		  				
		  				$commentstatus = 1;
		  				if($commentid)
		  					$commentstatus = 2;
		  				$this->Order_model->update_by_where(array('id'=>$orderid), array('commentstatus'=>$commentstatus));

		  				$this->load->service('num_service');
		  				$this->num_service->set_user_num($touserid,'be_commentnum');
		  				$this->num_service->set_user_num($touserid,'be_commentnum_new',1);
						$this->num_service->set_user_num($this->thatUser['id'],'commentnum');
						$this->num_service->set_user_num($this->thatUser['id'],'commentnum_new',1);

						redirect('/m/comment');
						exit;
					}
					
				}

  				
  			}

		}

		$get_orderid = _get_key_val($this->input->get('orderid'),true);
		$get_commentid = _get_key_val($this->input->get('commentid'),true);

		$info = array('orderid'=>$get_orderid,'commentid'=>$get_commentid);

		$result = array(
			'info' => $info,
			);
		$this->load->view('m/commentadd',$result);
	}
        
        
    // 删除评论    
    function delCommentById()
    {
        $resArr = array('code'=>0, 'error_msg'=> '');
        $commmentId = $this->input->post('comment_id');
        
        if (!empty($commmentId) && is_numeric($commmentId)) {
            // 删除ID
            $flag = $this->Comment_model->delCommentById($commmentId);
            if (!empty($flag)) {
                $resArr['code'] = 200;
            } else {
                $resArr['code'] = 202;
                $resArr['error_msg'] = '删除失败!!';
            }
        } else {
              $resArr['code'] = 201;
              $resArr['error_msg'] = '评论ID不合法';
        }
        
        return $this->view->json($resArr);
    }
    
    // 编辑评论展示
    public function edit()
    {
        $commendId = _get_key_val($this->input->get('orderid'), true);
        if (!empty($commendId) && is_numeric($commendId)) {
            // 获取内容
            $commendInfo = $this->Comment_model->get_info_by_id($commendId);
           
            $result = array(
                'info' => $commendInfo
            );
            
            $this->load->view('m/comment_edit', $result);
        } else {
            // 没有
            redirect('m/comment');
        }
    }
    
    // 编辑内容
    public function editsave()
    {
        $href = '/m/comment';
        $msg = '修改失败！！';
        
        if ($this->input->is_post()) {
            $config[] =  array(
                'field'   => 'memo', 
                'label'   => '留言', 
                'rules'   => 'trim|required'
            );  
            
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() === TRUE) {
                // 修改内容
                $commentId = $this->input->post('commentid');
                $memo = $this->input->post('memo');
                $flag = $this->Comment_model->editCommentMemoById($commentId, $memo); 
            }
            
            if (!empty($flag)) {
                $msg = '修改成功!!';
            } else {
                $href = '/m/comment/edit?orderid='._get_key_val($commentId);
            } 
        }
        
        redirect($href);
    }
}